package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.search.ArticleIndexConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vo.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleSearchServiceImpl  implements ArticleSearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    ApUserSearchService apUserSearchService;
    /**
     * ES文章分页搜索
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        //检查参数
        String searchWords = userSearchDto.getSearchWords();
        if (userSearchDto == null || StringUtils.isBlank(searchWords)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (userSearchDto.getPageSize() == 0) {
            userSearchDto.setPageSize(10);
        }
        if (userSearchDto.getMinBehotTime() == null) {
            userSearchDto.setMinBehotTime(new Date());
        }
        //***如果是首页记录搜索关键字
        ApUser user = AppThreadLocalUtils.getUser();
        if (user !=null && userSearchDto.getFromIndex() == 0) {
            userSearchDto.setEntryId(user.getId());
            // 异步调用保存用户输入关键词记录
            //TODO
           apUserSearchService.insert(userSearchDto);
        }
        //构建查询执行查询
        SearchRequest searchRequest = new SearchRequest(ArticleIndexConstants.ARTICLE_INDEX_NAME);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建查询条件和过滤等
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 关键词查询
        boolQueryBuilder.must(QueryBuilders.matchQuery("title", userSearchDto.getSearchWords()));
        // 查询小于mindate的数据
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(userSearchDto.getMinBehotTime()));
        // 分页
        sourceBuilder.from(0);
        sourceBuilder.size(userSearchDto.getPageSize());
        // 按照发布时间倒序
        sourceBuilder.sort("publishTime", SortOrder.DESC);
        // 高亮 三要素
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");
        sourceBuilder.highlighter(highlightBuilder);
        sourceBuilder.query(boolQueryBuilder);
        searchRequest.source(sourceBuilder);
        try {
            //3 解析结果 封装结果
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits searchHits = searchResponse.getHits();
            List<SearchArticleVo> resultList = new ArrayList<>();
            //总记录数
            long total = searchHits.getTotalHits().value;
            log.info("search result total:{}", total);
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String jsonString = hit.getSourceAsString();
                SearchArticleVo apArticle = JSON.parseObject(jsonString, SearchArticleVo.class);
                // 获取高亮结果集
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                // 保留高亮标题
                String title = StringUtils.join(titles);
                if (StringUtils.isNotBlank(title)) {
                    apArticle.setTitle(title);
                    apArticle.setImages(webSite + apArticle.getImages());
                }
                resultList.add(apArticle);
            }
            //返回数据
            return ResponseResult.okResult(resultList);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("search result error:{}", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public void saveArticle(SearchArticleVo article) {
        IndexRequest request = new IndexRequest("app_info_article");
        request.id(String.valueOf(article.getId()));
        request.source(JSON.toJSONString(article), XContentType.JSON);
        try {
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库添加文章数据失败: {}",article);
        }
    }

    @Override
    public void deleteArticle(String articleId) {
        DeleteRequest request = new DeleteRequest("app_info_article",String.valueOf(articleId));
        try {
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引库删除文章数据失败: {}",e.getMessage());
        }
    }
}
